package com.atguigu.ssyx;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Demo3 {
    public static void main1(String[] args) {

        ExecutorService executorService = Executors.newFixedThreadPool(3);
        CompletableFuture<Integer> uCompletableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("当前线程是:" + Thread.currentThread().getName());
            int value = 1024;
            return value;
        }, executorService).whenCompleteAsync((res, ex) -> {
            System.out.println("当前data:" + res);
            System.out.println("当前线程是:" + ex);

        });
    }

    public static void main2(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        CompletableFuture<Integer> futureA = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName());
            int value = 1024;
            System.out.println("任务一");
            return value;
        }, executorService);

        CompletableFuture<Integer> futureB = futureA.thenApply((res) -> {
            System.out.println("任务二");
            System.out.println(Thread.currentThread().getName());
            res = res * 2;
            System.out.println(res);
            return res;
        });

        CompletableFuture<Integer> futureC = futureB.thenApply((res) -> {
            System.out.println("任务三");
            res = res * 2;

            return res;
        });
        System.out.println(futureC.get());
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(4);
        CompletableFuture<Integer> futureA = CompletableFuture.supplyAsync(() -> {
            System.out.println("线程1:" + Thread.currentThread().getName());
            int value = 1024;
//            sleep(1000);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(value);

            return value;
        }, executorService);

        CompletableFuture<Integer> futureB = CompletableFuture.supplyAsync(() -> {
            System.out.println("线程2:" + Thread.currentThread().getName());
            int value = 200;
            System.out.println(value);
            return value;
        }, executorService);

        CompletableFuture<Void> all = CompletableFuture.allOf(futureA, futureB);
        CompletableFuture<Object> any = CompletableFuture.anyOf(futureA, futureB);
        any.get();
        all.get();
        System.out.println("over...");
    }
}

